import React from 'react';
import { root } from './root';
import ReactDOM from "react-dom"
let state = [];
let setter = []
let stateIndex = 0
function createState(index) {
  return function (newState) {
    state[index] = newState
    render()
  }
}
function useState(initValue) {
  state[stateIndex] = state[stateIndex] ? state[stateIndex] : initValue
  setter.push(createState(stateIndex))
  let value = state[stateIndex]
  let setValue = setter[stateIndex]
  stateIndex++
  return [value, setValue]
}
function render() {
  stateIndex = 0
  effectIndex = 0
  root.render(
    <React.StrictMode>
      <App />
    </React.StrictMode>
  );
}
let prevDepsAry = []
let effectIndex = 0
function useEffect(callBack, depsAry) {
  // 判断 callBack是不是函数
  if (Object.prototype.toString.call(callBack) !== "[object Function]") throw new Error("useEffect第一个参数必须是一个函数")
  // 判断 depsAry 有没有被传递

  if (typeof depsAry === 'undefined') {
    callBack()
  } else {
    // 判断 depsAry 是不是数组
    if (Object.prototype.toString.call(depsAry) !== "[object Array]") throw new Error("useEffect第二个参数必须是一个数组")
    let prevArr = prevDepsAry[effectIndex]
    const hasChange = prevArr ? depsAry.every((item, index) => {
      return item === prevArr[index]
    }) == false : true
    if (hasChange) {
      callBack()
    }
    prevDepsAry[effectIndex] = depsAry
    effectIndex++
  }
}
function useReducer(reducer,initState) { 
    const [state,setState] = useState(initState)
    function dispatch(action){
        const newState = reducer(state,action)
        setState(newState)
    }
    return [state,dispatch]
}
function App() {
  const [count, setCount] = useState(0)
  const [name, setName] = useState("张三")
  useEffect(() => {
    console.log("hello")
  }, [])
  useEffect(() => {
    console.log("word")
  }, [])
  function reducer(state, action) {
    switch (action.type) {
      case "increment":
        return state + 1
      case "decrement":
        return state - 1
      default:
        return state
    }
  }
  const [num, dispatch] = useReducer(reducer, 0)
  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>11</button>
      <p>{name}</p>
      <button onClick={() => setName("李四")}>11</button>
      <h2>{num}</h2>
      <button onClick={()=>dispatch({type:"increment"})}>+1</button>
      <button onClick={()=>dispatch({type:"decrement"})}>-1</button>
    </div>
  )
}
export default App;
